using UnityEngine;
using Cinemachine;
using Framework;

namespace Game
{
    public class CharacterScene : BaseFakeScene
    {
        [SerializeField]
        private CinemachineVirtualCamera m_VirutalCamera;

        [SerializeField]
        private Transform m_CharacterParent;

        public CharacterMotor Character { get; private set; }

        private Vector3 m_CameraTempPos;
        private Vector3 m_CameraLookAtPos;
        private float m_CameraDistance;
        private float m_CameraRotation = 0;

        protected override void Awake()
        {
            base.Awake();
            CinemachineBrain.SoloCamera = this.m_VirutalCamera;
            this.m_CameraTempPos = this.m_VirutalCamera.transform.position;
            this.m_CameraLookAtPos = new Vector3(0, this.m_CameraTempPos.y, 0);
            this.m_CameraDistance = this.m_CameraTempPos.z;
        }

        public async FTask RefreshCharacter(string name)
        {
            string pathCharacter = AssetUtility.GetWarriorPath(name);
            GameObject prefabCharacter = await GameEntry.Resource.LoadPrefabAsync(pathCharacter);
            GameObject goCharacter = GameObject.Instantiate(prefabCharacter, this.m_CharacterParent);
            goCharacter.SetLayerRecursively(LayerMask.NameToLayer("CharacterShow"));
            this.Character = goCharacter.GetComponent<CharacterMotor>();
        }

        protected override void OnDestroy()
        {
            CinemachineBrain.SoloCamera = null;
            base.OnDestroy();
        }

        public void RotateCamera(float delta)
        {
            this.m_CameraRotation = (this.m_CameraRotation + delta * 0.1f) % 360;
            float radian = this.m_CameraRotation * Mathf.PI / 180;
            float sin = Mathf.Sin(radian) * this.m_CameraDistance;
            float cos = Mathf.Cos(radian) * this.m_CameraDistance;
            // Log.Info("RotateCamera {0} {1} {2} {3}", this.m_CameraRotation, sin, cos, this.m_CameraLookAtPos);
            this.m_CameraTempPos.x = sin;
            this.m_CameraTempPos.z = cos;
            this.m_VirutalCamera.transform.position = this.m_CameraTempPos;
            this.m_VirutalCamera.transform.LookAt(this.m_CameraLookAtPos);
        }
    }
}